//
//  ShowVideoViewController.m
//  ImagePicker
//
//  Created by YH on 2018/5/2.
//  Copyright © 2018年 王跃. All rights reserved.
//

#import "ShowVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SmallVideoConfig.h"

#define DeviceWith          (SmallVideoSCREEN_WIDTH + 10)
#define DeviceHeight        (SmallVideoSCREEN_HEIGHT + 16)

@interface ShowVideoViewController ()

@property (nonatomic, strong) AVPlayerLayer     *playerLayer;
@property (nonatomic, strong) AVPlayer          *player;
@property (nonatomic, strong) UIImageView       *backImageView;
@end

@implementation ShowVideoViewController

- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNotification];
    [self setupUI];

}

- (void)initNotification
{
    // 添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playDidEnd)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:self.player];
}

- (void)setUrl:(NSURL *)url
{
    _url = url;
    [self showVideoWithUrl:self.url];
}

- (void)setImage:(UIImage *)image
{
    _image = image;
    self.backImageView.image = image;
}

- (void)setupUI
{
    self.backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWith, DeviceHeight)];
    self.backImageView.backgroundColor = [UIColor clearColor];
    self.backImageView.center = CGPointMake((DeviceWith)/ 2,
                                            (DeviceHeight) / 2);
    [self.view addSubview:self.backImageView];
}

- (void)showVideoWithUrl:(NSURL *)videoUrl
{
    self.player = [[AVPlayer alloc] initWithURL:videoUrl];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.playerLayer.frame = CGRectMake(0, 0, DeviceWith, DeviceHeight);
    self.playerLayer.backgroundColor = [UIColor clearColor].CGColor;
    self.playerLayer.position = CGPointMake((DeviceWith)/ 2,
                                              (DeviceHeight) / 2);
    [self.view.layer addSublayer:self.playerLayer];
    [self.player play];
}

- (void)playDidEnd
{
    __weak typeof(self) waekSelf = self;
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        [waekSelf.player play];
    }];
}

- (void)removePlayLayer
{
    [self.playerLayer removeFromSuperlayer];
    self.player = nil;
}

@end
